/**
 * @Author: colpu
 * @Date: 2025-03-29 19:38:16
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-10-17 15:18:43
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import assert from "assert";
import is from "is-type-of";
import debugFactory from "debug";
const debug = debugFactory("core:loader/context_loader");
const CLASSLOADER = Symbol("classLoader");
import { EXPORTS } from "../constants.js";
import FileLoader from "./file_loader.js";

class ClassLoader {
  constructor(options) {
    assert(options.ctx, "options.ctx是必需的");
    const properties = options.properties;
    this._cache = new Map();
    this._ctx = options.ctx;
    for (const property in properties) {
      this.defineProperty(property, properties[property]);
    }
  }
  defineProperty(property, values) {
    Object.defineProperty(this, property, {
      get() {
        let instance = this._cache.get(property);
        if (!instance) {
          instance = getInstance(values, this._ctx);
          this._cache.set(property, instance);
        }
        return instance;
      },
    });
  }
}

/**
 * @class ContextLoader 上下文加载
 * @param {Object} options 配置
 */
export default class ContextLoader extends FileLoader {
  constructor(options) {
    assert(options, "必须设置options");
    debug("contextLoader constructor %s", options);
    super(options);
    const target = options.target;
    const app = this.options.inject;
    const property = options.property;
    // define ctx.service
    Object.defineProperty(app.context, property, {
      get() {
        // distinguish property cache,
        // e.x. ctx.service1 and ctx.service2 have different cache
        if (!this[CLASSLOADER]) {
          this[CLASSLOADER] = new Map();
        }
        const classLoader = this[CLASSLOADER];
        let instance = classLoader.get(property);
        if (!instance) {
          instance = getInstance(target, this);
          classLoader.set(property, instance);
        }
        return instance;
      },
    });
  }
}

function getInstance(values, ctx) {
  const DynamicClass = values[EXPORTS] ? values : null;
  let instance;
  if (DynamicClass) {
    if (is.class(DynamicClass)) {
      instance = new DynamicClass(ctx);
    } else {
      // it's just an object
      instance = DynamicClass;
    }
    // Can't set property to primitive, so check again
    // e.x. module.exports = 1;
  } else if (is.primitive(values)) {
    instance = values;
  } else {
    instance = new ClassLoader({
      ctx,
      properties: values,
    });
  }
  return instance;
}
